// pages/judge/review/review.js
const app = getApp();

Page({
  data: {
    applicationId: "",
    studentInfo: {},
    transcriptInfo: {},
    researchList: [],
    progress: [],
    scores: {
      academic: 0,
      research: 0,
    },
    totalScore: 0,
    reviewComment: "",
    recommendation: "",
  },

  onLoad(options) {
    const { id } = options;
    this.setData({ applicationId: id });
    this.loadApplicationDetail();
  },

  async loadApplicationDetail() {
    try {
      const local = require("../../../utils/local");
      const result = local.getJudgeApplicationDetail(this.data.applicationId);
      if (result.success) {
        this.setData({
          studentInfo: result.data.student,
          transcriptInfo: result.data.transcript,
          researchList: result.data.research || [],
          progress: result.data.progress || [],
        });
        const auto = local.computeAutoScore(this.data.applicationId);
        this.setData({
          scores: { academic: auto.academic, research: auto.research },
          totalScore: auto.total,
        });
      }
    } catch (error) {
      console.error("加载申请详情失败:", error);
    }
  },

  // 远程详情已移除，改为本地

  // 自动评分，移除手动输入

  onCommentInput(e) {
    this.setData({ reviewComment: e.detail.value });
  },

  setRecommendation(e) {
    const recommendation = e.currentTarget.dataset.value;
    this.setData({ recommendation });
  },

  viewTranscript() {
    wx.navigateTo({
      url: `/pages/judge/transcript/transcript?id=${this.data.applicationId}`,
    });
  },

  downloadTranscript() {
    wx.showLoading({ title: "下载中..." });

    // 模拟下载过程
    setTimeout(() => {
      wx.hideLoading();
      wx.showToast({
        title: "下载成功",
        icon: "success",
      });
    }, 2000);
  },

  previewFile(e) {
    const url = e.currentTarget.dataset.url;
    wx.previewImage({
      urls: [url],
      current: url,
    });
  },

  async saveDraft() {
    wx.showLoading({ title: "保存中..." });

    try {
      const result = await this.saveReviewDraft();
      if (result.success) {
        wx.showToast({
          title: "保存成功",
          icon: "success",
        });
      } else {
        wx.showToast({
          title: result.message || "保存失败",
          icon: "error",
        });
      }
    } catch (error) {
      console.error("保存草稿失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "error",
      });
    } finally {
      wx.hideLoading();
    }
  },

  saveReviewDraft() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${app.globalData.baseUrl}/judge/review/draft`,
        method: "POST",
        header: {
          Authorization: `Bearer ${wx.getStorageSync("token")}`,
          "Content-Type": "application/json",
        },
        data: {
          applicationId: this.data.applicationId,
          scores: this.data.scores,
          comment: this.data.reviewComment,
          recommendation: this.data.recommendation,
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve({ success: true, data: res.data });
          } else {
            resolve({ success: false, message: res.data.message });
          }
        },
        fail: reject,
      });
    });
  },

  async submitReview() {
    if (!this.validateReview()) return;

    wx.showModal({
      title: "确认提交",
      content: "提交后将无法修改，确认提交评审结果吗？",
      success: async (res) => {
        if (res.confirm) {
          await this.doSubmitReview();
        }
      },
    });
  },

  validateReview() {
    const { academic, research, comprehensive } = this.data.scores;
    const { reviewComment, recommendation } = this.data;

    if (!academic || !research || !comprehensive) {
      wx.showToast({
        title: "请填写所有评分项",
        icon: "none",
      });
      return false;
    }

    if (!reviewComment.trim()) {
      wx.showToast({
        title: "请填写评审意见",
        icon: "none",
      });
      return false;
    }

    if (!recommendation) {
      wx.showToast({
        title: "请选择推荐结果",
        icon: "none",
      });
      return false;
    }

    return true;
  },

  async doSubmitReview() {
    wx.showLoading({ title: "提交中..." });

    try {
      const result = await this.submitReviewRequest();
      if (result.success) {
        wx.showToast({
          title: "提交成功",
          icon: "success",
        });

        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      } else {
        wx.showToast({
          title: result.message || "提交失败",
          icon: "error",
        });
      }
    } catch (error) {
      console.error("提交评审失败:", error);
      wx.showToast({
        title: "网络错误，请重试",
        icon: "error",
      });
    } finally {
      wx.hideLoading();
    }
  },

  approveStage() {
    const local = require("../../../utils/local");
    const res = local.judgeUpdateStage(this.data.applicationId, "approve");
    if (res.success) {
      wx.showToast({ title: "已通过当前阶段", icon: "success" });
      this.loadApplicationDetail();
      this.suggestNextApplication();
    } else {
      wx.showToast({ title: res.message || "操作失败", icon: "error" });
    }
  },

  rejectStage() {
    const local = require("../../../utils/local");
    const res = local.judgeUpdateStage(this.data.applicationId, "reject");
    if (res.success) {
      wx.showToast({ title: "已退回", icon: "success" });
      this.loadApplicationDetail();
      this.suggestNextApplication();
    } else {
      wx.showToast({ title: res.message || "操作失败", icon: "error" });
    }
  },

  suggestNextApplication() {
    // 查找下一条待评审申请
    try {
      const local = require("../../../utils/local");
      const app = getApp();
      const judgeInfo =
        app.globalData.userInfo || wx.getStorageSync("userInfo") || {};
      const dept = judgeInfo.department || "书院";
      const listRes = local.getJudgeApplications("pending", dept);
      const list = (listRes && listRes.data) || [];
      if (!list.length) {
        wx.showModal({
          title: "评审完成",
          content: "暂无更多待评审申请，是否返回上一页？",
          success: (r) => {
            if (r.confirm) wx.navigateBack();
          },
        });
        return;
      }
      const idx = list.findIndex(
        (x) => String(x.id) === String(this.data.applicationId)
      );
      const next = idx >= 0 && idx < list.length - 1 ? list[idx + 1] : list[0];
      if (!next || String(next.id) === String(this.data.applicationId)) {
        // 只有当前一个，提示完成
        wx.showModal({
          title: "提示",
          content: "已处理该申请。是否继续查看待评审列表？",
          success: (r) => {
            if (r.confirm) wx.navigateBack();
          },
        });
        return;
      }
      wx.showModal({
        title: "跳转下一份",
        content: `是否前往下一份申请（${next.studentName || next.id}）？`,
        success: (r) => {
          if (r.confirm) {
            wx.redirectTo({ url: `/pages/judge/review/review?id=${next.id}` });
          }
        },
      });
    } catch (_) {}
  },

  submitReviewRequest() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: `${app.globalData.baseUrl}/judge/review/submit`,
        method: "POST",
        header: {
          Authorization: `Bearer ${wx.getStorageSync("token")}`,
          "Content-Type": "application/json",
        },
        data: {
          applicationId: this.data.applicationId,
          scores: this.data.scores,
          totalScore: this.data.totalScore,
          comment: this.data.reviewComment,
          recommendation: this.data.recommendation,
        },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve({ success: true, data: res.data });
          } else {
            resolve({ success: false, message: res.data.message });
          }
        },
        fail: reject,
      });
    });
  },
});
